﻿using System;
using TMPro;
using UnityEngine;
using UnityEngine.U2D;
using UnityEngine.UI;

namespace HEFramework
{
    public static class GameUISystem
    {
        [EntitySystem]
        public class GameUIAwakeSystem : AwakeSystem<GameUI>
        {
            protected override void Awake(GameUI _self)
            {
                _self.AddChild<UnityObjectComponent>();
                _self.Open();
            }
        }

        [EntitySystem]
        public class GameUIUpdateSystem : UpdateSystem<GameUI>
        {
            protected override void Update(GameUI _self)
            {
                _self.Update();
            }
        }

        [EntitySystem]
        public class GameUIDestroySystem : DestroySystem<GameUI>
        {
            protected override void Destroy(GameUI _self)
            {
                _self.Close();
            }
        }


        public static void Open(this GameUI _self)
        {
            var uc = _self.GetSceneChild<UIComponent>();
            if (uc == null)
            {
                return;
            }

            uc.PushUIAsync(eUIFlag.Game, _ =>
            {
                _self.UIWindowBehaviour = _;
                _self.Bind();
                _self.Update(true);
            });
        }

        public static void Bind(this GameUI _self)
        {
            if (_self.UIWindowBehaviour == null)
            {
                return;
            }

            var uc = _self.GetChild<UnityObjectComponent>();
            if (uc == null)
            {
                return;
            }

            _self.UIWindowBehaviour.GetButton("Button_Element").RegisterUpEvent(_self.Open_ElementUI);
            _self.UIWindowBehaviour.GetButton("Button_MenuItem0").RegisterUpEvent(_self.Open_TeamUI);
            _self.UIWindowBehaviour.GetButton("Button_MenuItem1").RegisterUpEvent(_self.Open_TrialUI);
            _self.UIWindowBehaviour.GetButton("Button_MenuItem2").RegisterUpEvent(_self.Open_SummonUI);
            var legacyBar = _self.UIWindowBehaviour.GetTransform("Transform_LegacyBar");
            for (int i = 0; i < legacyBar.childCount; i++)
            {
                int index = i;
                var button = uc.Get<Button>(legacyBar.GetChild(i).gameObject);
                button.onClick.RemoveAllListeners();
                button.onClick.AddListener(() => { _self.Open_LegacyInfo(index); });
            }
        }

        public static void Update(this GameUI _self, bool _isNew = false)
        {
            if (_self.UIWindowBehaviour == null)
            {
                return;
            }

            var pc = _self.GetSceneChild<PrefabComponent>();
            var rc = _self.GetSceneChild<ResourcesComponent>();
            var dc = _self.GetSceneChild<DataTableComponent>();
            var uc = _self.GetChild<UnityObjectComponent>();
            if (pc == null || rc == null || dc == null || uc == null)
            {
                return;
            }

            //更新回合信息
            Round round = _self.GetSceneChild<Round>();
            if (round != null)
            {
                _self.UIWindowBehaviour.GetTMPText("TMPText_RoundCounts").SetText("回合：" + (round.Round_Counts + 1));
                _self.UIWindowBehaviour.GetTMPText("TMPText_RoundSeconds").SetText(Math.Ceiling((float)round.Round_Seconds).ToString());
            }

            //更新玩家信息
            Player player = _self.GetSceneChild<Player>();
            if (player != null)
            {
                _self.UIWindowBehaviour.GetTMPText("TMPText_Golds").SetText(((int)player.G).ToString());
                _self.UIWindowBehaviour.GetTMPText("TMPText_Kills").SetText(((int)player.K).ToString());
            }

            //更新五行元素信息
            Element element = _self.GetSceneChild<Element>();
            var element_table = dc.LoadDataTable<DRElement>();
            if (element != null)
            {
                var element_transform = _self.UIWindowBehaviour.GetButton("Button_Element").GetTransform();
                for (int i = 0; i < element_transform.childCount; i++)
                {
                    var element_item = element_transform.GetChild(i);
                    var element_id = (int)(eElement.Gold + i);
                    var element_lv = element.Elements[element_id];
                    var element_lvs = element_table.GetData(element_id).Levels;
                    var element_max_lv = element_lvs[element_lvs.Length - 1];
                    var element_text = uc.Get<TMP_Text>(element_item.GetChild(1).gameObject);
                    element_text.text = element_lv + "/" + element_max_lv;
                }
            }


            if (_isNew)
            {
                //更新遗物图标
                var legacy = _self.GetSceneChild<Legacy>();
                var legacyBar = _self.UIWindowBehaviour.GetTransform("Transform_LegacyBar");
                var childCount = legacyBar.childCount;
                for (int i = 0; i < childCount; i++)
                {
                    var button = legacyBar.GetChild(i).gameObject;
                    var child = button.transform.GetChild(0).gameObject;
                    var image = uc.Get<Image>(child);
                    if (i >= legacy.LegacyPlaces.Count)
                    {
                        image.gameObject.SetActive(false);
                    }
                    else
                    {
                        int legacyID = legacy.LegacyPlaces[i];
                        var legacy_data = dc.LoadDataTable<DRLegacy>().GetData(legacyID);
                        rc.Assets.LoadAssetAsync<UnityEngine.Object>(legacy_data.ABPath, legacy_data.ABName, ResourceConfig.Extension.TEXTURE, _ =>
                        {
                            Sprite sprite = null;
                            if (_ is Texture2D t)
                            {
                                sprite = Sprite.Create(t, new Rect(0, 0, t.width, t.height), new Vector2(0.5f, 0.5f));
                            }

                            if (_ is Sprite s)
                            {
                                sprite = s;
                            }

                            image.sprite = sprite;
                            image.gameObject.SetActive(true);
                        });
                    }
                }
            }
        }

        public static void Close(this GameUI _self)
        {
            if (_self.UIWindowBehaviour != null)
            {
                _self.UIWindowBehaviour.Hide();
                _self.UIWindowBehaviour = null;
            }
        }

        public static void Open_ElementUI(this GameUI _self)
        {
            _self.GetSceneChild<ElementUI>().Open();
        }

        public static void Open_TeamUI(this GameUI _self)
        {
            _self.GetSceneChild<TeamUI>().Open();
        }

        public static void Open_TrialUI(this GameUI _self)
        {
            _self.GetSceneChild<TrialUI>().Open();
        }

        public static void Open_SummonUI(this GameUI _self)
        {
            _self.GetSceneChild<SummonUI>().Open();
        }

        public static void Open_LegacyInfo(this GameUI _self, int _index)
        {
            var legacy = _self.GetSceneChild<Legacy>();
            if (legacy == null)
            {
                return;
            }

            if (_index >= legacy.LegacyPlaces.Count)
            {
                return;
            }

            _self.GetSceneChild<LegacyInfoUI>().OpenByID(legacy.LegacyPlaces[_index]);
        }
    }
}